package com.coolcode.service.impl;

import com.coolcode.dto.LoginReqDto;
import com.coolcode.dto.LoginRespDto;
import com.coolcode.entity.UserInfo;
import com.coolcode.entity.LoginUserInfo;
import com.coolcode.enums.ExceptionErrorCode;
import com.coolcode.exception.ValidationException;
import com.coolcode.service.LoginService;
import com.coolcode.util.JWTUtil;
import com.coolcode.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    private long oneDay = 60 * 60 * 24 * 1000;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public LoginRespDto login(LoginReqDto loginReqDto) {
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginReqDto.getUsername(), loginReqDto.getPassword());

        // AuthenticationManager 进行用户认证
        Authentication authentication;
        try{
            authentication = authenticationManager.authenticate(authenticationToken);
        }catch(Exception e){
            throw new ValidationException(ExceptionErrorCode.LOGIN_FAIL, e.getMessage());
        }

        // 认证通过 生成token(jwt)返回
        LoginUserInfo loginUserInfo = (LoginUserInfo) authentication.getPrincipal();
        UserInfo userInfo = loginUserInfo.getUserInfo();

        LoginRespDto loginRespDto = new LoginRespDto();
        loginRespDto.setUsername(userInfo.getUserName());
        loginRespDto.setPassword(userInfo.getPassword());
        loginRespDto.setToken(JWTUtil.generateToken(userInfo, oneDay));

        // 把完整的用户登录信息存入redis
        redisUtils.set(loginUserInfo.getUsername(), loginUserInfo);
        return loginRespDto;
    }

    @Override
    public void logout() {
        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUserInfo principal = (LoginUserInfo)authentication.getPrincipal();
        Integer id = principal.getUserInfo().getId();
        
        // 根据id生产key并删除redis的值
        String redisKey = "" + id;
        redisUtils.delete(redisKey);
    }
}
